package com.xd.core.business.controller;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xd.common.ascept.CheckSign;
import com.xd.common.constant.SysConstant;
import com.xd.common.exception.XkdException;
import com.xd.common.util.SecurityUtil;
import com.xd.core.api.mapper.ChannelPayTowMapper;
import com.xd.core.business.dto.*;
import com.xd.core.business.entity.Contract;
import com.xd.core.business.mapper.ContractMapper;
import com.xd.core.business.mapper.MortgageMapper;
import com.xd.core.business.mapper.OutOrderInfoMapper;
import com.xd.core.business.service.IMortgageService;
import com.xd.core.business.service.IOutInfoService;
import com.xd.core.business.service.IRepaymentScheduleService;
import com.xd.core.business.service.ISurrenderinfoService;
import com.xd.core.business.vo.*;
import com.xd.core.company.entity.Company;
import com.xd.core.company.mapper.CompanyMapper;
import com.xd.core.company.service.ICompanyService;
import com.xd.core.mission.entity.MissionCenterInfo;
import com.xd.core.mission.mapper.MissionCenterInfoMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 放款表 前端控制器
 * </p>
 *
 * @author ZX
 * @since 2025-02-27
 */
@Api(tags = "放款")
@RestController
@RequestMapping("/business/out-info")
public class OutInfoController {

    @Autowired
    private IOutInfoService iOutInfoService;
    @Autowired
    private MissionCenterInfoMapper missionCenterInfoMapper;
    @Autowired
    private OutOrderInfoMapper outOrderInfoMapper;
    @Autowired
    private ICompanyService iCompanyService;
    @Autowired
    private IMortgageService iMortgageService;
    @Autowired
    private IRepaymentScheduleService iRepaymentScheduleService;
    @Autowired
    private CompanyMapper companyMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private MortgageMapper mortgageMapper;
    @Autowired
    private ChannelPayTowMapper channelPayTowMapper;
    @Autowired
    private ISurrenderinfoService surrenderinfoService;


    @PreAuthorize("hasAnyAuthority('sys:Lending-GoLend','sys:Lending-Lending')")
    @CheckSign
    @ApiOperation("去放款")
    @PostMapping("/insertOutInfo")
    public void insertOutInfo(@RequestBody OutInfoDto outInfo) throws Exception {
        iOutInfoService.addOutInfo(outInfo);
    }

    @PreAuthorize("hasAnyAuthority('sys:PolicyDisbursement-GoLend')")
    @CheckSign
    @ApiOperation("保单贷--去放款")
    @PostMapping("/insertInsuranceOutInfo")
    public void insertInsuranceOutInfo(@RequestBody OutInfoDto outInfo) throws Exception {
        iOutInfoService.insertInsuranceOutInfo(outInfo);
    }

    @ApiOperation("保单贷--去放款弹窗")
    @GetMapping("/getInsuranceOutWindow/{id}")
    public OutInsuranceWindowVo getInsuranceOutWindow(@PathVariable Integer id) {
        return iOutInfoService.getInsuranceOutWindow(id);
    }

    @PreAuthorize("hasAnyAuthority('sys:Lending-AgainLend')")
    @CheckSign
    @ApiOperation("重新放款")
    @PostMapping("/againOutInfo")
    public void againOutInfo(@RequestBody OutInfoDto outInfo) throws Exception {
        iOutInfoService.againOutInfo(outInfo);
    }

    @PreAuthorize("hasAnyAuthority('sys:PolicyDisbursement-ReLending')")
    @CheckSign
    @ApiOperation("保单贷-重新放款")
    @PostMapping("/InsuranceAgainOutInfo")
    public void InsuranceAgainOutInfo(@RequestBody OutInfoDto outInfo) throws Exception {
        iOutInfoService.InsuranceAgainOutInfo(outInfo);
    }

    @PreAuthorize("hasAnyAuthority('sys:Lending-viewDetails','sys:Lending')")
    @ApiOperation("放款列表")
    @PostMapping("/outInfoList")
    public Page<OutInfoPageVo> outInfoList(@RequestBody OutInfoQuery query) {
        return iOutInfoService.getList(query);
    }

    @ApiOperation("外接app--放款列表")
    @PostMapping("/outInfoAppList")
    public Page<OutInfoPageAppVo> outInfoAppList(@RequestBody OutInfoAppQuery query) {
        return iOutInfoService.outInfoAppList(query);
    }

    @ApiOperation("导出外接app--放款列表")
    @PostMapping("/exportOutInfoAppList")
    public void exportOutInfoAppList(@RequestBody OutInfoAppQuery query) {
        //插入数据状态是正在导出
        MissionCenterInfo missionCenterInfo = new MissionCenterInfo();
        missionCenterInfo.setCompanyId(SecurityUtil.getLoginCompanyId());
        missionCenterInfo.setFileStatus(SysConstant.YSZT_FILE_STATUS_ONE);
        missionCenterInfo.setCreateTime(new Date());
        missionCenterInfo.setUserId(SecurityUtil.getLoginUserId());
        missionCenterInfoMapper.insert(missionCenterInfo);
        iOutInfoService.exportOutInfoAppList(query, missionCenterInfo.getId());
    }

    @ApiOperation("外接app--放款详情")
    @GetMapping("/outInfoAppDetail/{incomingId}")
    public OutInfoAppVo outInfoAppDetail(@PathVariable Integer incomingId) {
        return iOutInfoService.outInfoAppDetail(incomingId);
    }

    @ApiOperation("外接app--放款详情--合同列表")
    @GetMapping("/outInfoContractList/{outId}")
    public List<ContractAppListVo> outInfoContractList(@PathVariable Integer outId) {
        return contractMapper.getList(outId);
    }

    @ApiOperation("外接app--业务详情--还款计划")
    @PostMapping("/getOutRepaymentPlanApp")
    public RepaymentScheduleAppVo getOutRepaymentPlanApp(@RequestBody RepaymentScheduleAppDto repaymentScheduleAppDto) {
        return iRepaymentScheduleService.getOutRepaymentPlan(repaymentScheduleAppDto);
    }

    @PreAuthorize("hasAnyAuthority('sys:PolicyDisbursement-viewDetails')")
    @ApiOperation("保单贷--放款列表")
    @PostMapping("/outInsuranceInfoList")
    public Page<OutInsuranceInfoPageVo> outInsuranceInfoList(@RequestBody OutInfoQuery query) {
        return iOutInfoService.outInsuranceInfoList(query);
    }

    @ApiOperation("导出放款列表")
    @PostMapping("/exportOutInfoList")
    public void exportOutInfoList(@RequestBody OutInfoQuery query) {
        //插入数据状态是正在导出
        MissionCenterInfo missionCenterInfo = new MissionCenterInfo();
        missionCenterInfo.setCompanyId(SecurityUtil.getLoginCompanyId());
        missionCenterInfo.setFileStatus(SysConstant.YSZT_FILE_STATUS_ONE);
        missionCenterInfo.setCreateTime(new Date());
        missionCenterInfo.setUserId(SecurityUtil.getLoginUserId());
        missionCenterInfoMapper.insert(missionCenterInfo);
        iOutInfoService.exportIncomingInfoList(query, missionCenterInfo.getId());
    }

    @ApiOperation("放款详情")
    @GetMapping("/getOutDetail/{id}")
    public OutInfoVo getOutDetail(@PathVariable Integer id) {
        return iOutInfoService.getOutDetail(id);
    }

    @ApiOperation("业务详情--进件信息")
    @GetMapping("/getIncomingDetail/{id}")
    public OrderDetailIncomingInfoVo getIncomingDetail(@PathVariable Integer id) {
        return iOutInfoService.getIncomingDetail(id);
    }

    @ApiOperation("保单贷--业务详情--放款信息")
    @GetMapping("/getInsuranceIncomingDetail/{incomingId}")
    public OutInsuranceInfoVo getInsuranceIncomingDetail(@PathVariable Integer incomingId) {
        return iOutInfoService.getInsuranceIncomingDetail(incomingId);
    }

    @ApiOperation("保单贷--业务详情--放款信息--放款记录")
    @GetMapping("/getOutOrderList/{incomingId}/{payPass}")
    public List<OutInsuranceRecordVo> getOutOrderList(@PathVariable Integer incomingId, @PathVariable String payPass) {
        return iOutInfoService.getOutOrderList(incomingId, payPass);
    }

    @ApiOperation("业务详情--进件信息--资产信息")
    @GetMapping("/getOrderCustomerInfoVo/{id}")
    public IncomingInfoMortgageVo getOrderCustomerInfoVo(@PathVariable Integer id) {
        return iMortgageService.getDetail(id);
    }

    @ApiOperation("业务详情--放款记录")
    @PostMapping("/getOutRecordList")
    public Page<OutRecordVo> getOutRecordList(@RequestBody OutInfoDtoQuery query) {
        if (SysConstant.CHANNEL_TYPE_ONE.equals(query.getPayPass())) {
            PageHelper.startPage(query.getPageNum(), query.getPageSize());
            return (Page<OutRecordVo>) outOrderInfoMapper.getList(query);
        } else {
            PageHelper.startPage(query.getPageNum(), query.getPageSize());
            return (Page<OutRecordVo>) channelPayTowMapper.getList(query);
        }
    }

    @ApiOperation("还款计划列表（保单历史还款计划）")
    @PostMapping("/getRepaymentScheduleList/{debtId}")
    public List<RepaymentScheduleList> getRepaymentScheduleList(@PathVariable Integer debtId) {
        return iRepaymentScheduleService.getRepaymentScheduleList(debtId);
    }

    @ApiOperation("业务详情--还款计划")
    @PostMapping("/getOutRepaymentPlan")
    public RepaymentInfoVo getOutRepaymentPlan(@RequestBody RepaymentScheduleDto repaymentScheduleDto) {
        return iRepaymentScheduleService.getList(repaymentScheduleDto);
    }

    @ApiOperation("查看历史还款计划")
    @PostMapping("/getSurrenderDetail/{id}")
    public SurrenderDetailVo getSurrenderDetail(@PathVariable Integer id) {
        return surrenderinfoService.getSurrenderDetail(id);
    }

    @ApiOperation("退保后剩余应还本金和利息")
    @PostMapping("/getRemainAmount")
    public RemainAmountVo getRemainAmount(@RequestBody RepaymentScheduleDto repaymentScheduleDto) {
        return iRepaymentScheduleService.getRemainAmount(repaymentScheduleDto);
    }

    @ApiOperation("业务详情--还款详情信息")
    @PostMapping("/getRepayDetail")
    public RepayDetailVo getRepayDetail(@RequestBody RepaymentScheduleDto repaymentScheduleDto) {
        return iRepaymentScheduleService.getRepayDetail(repaymentScheduleDto);
    }

    @ApiOperation("业务详情--抵押公证信息")
    @GetMapping("/getMortgageDetail/{id}")
    public List<MortgageCerfifition> getMortgageDetail(@PathVariable Integer id) {
        return mortgageMapper.getList(id);
    }


    @ApiOperation("去放款弹窗详情")
    @GetMapping("/getOutDetailWindow/{id}")
    public OutInfoWindowVo getOutDetailWindow(@PathVariable Integer id) {
        return iOutInfoService.getOutDetail1(id);
    }

    @ApiOperation("放款账户余额")
    @GetMapping("/getOutAccountBalance/{companyId}/{payPass}")
    public OutBalanceVo getOutAccountBalance(@PathVariable Integer companyId, @PathVariable String payPass) {
        if (SysConstant.CHANNEL_TYPE_ONE.equals(payPass)) {
            return companyMapper.selectOutAccountBalance(companyId);
        } else {
            return companyMapper.selectOutAccountBalanceTwo(companyId);
        }
    }

    @ApiOperation("放款列表--进件机构下拉框")
    @GetMapping("/getInstitution")
    public List<Company> getInstitutions() {
        Integer companyId = SecurityUtil.getLoginCompanyId();
        if (companyId == 0) {
            return iCompanyService.list(new LambdaQueryWrapper<Company>().notIn(Company::getCompanyType, SysConstant.COMPANY_TYPE_THREE));
        } else {
            return iCompanyService.list(new LambdaQueryWrapper<Company>().eq(Company::getBlocId, companyId));
        }
    }

    @PreAuthorize("hasAnyAuthority('sys:Lending-ModifyAccount')")
    @ApiOperation("修改收款账户")
    @PostMapping("/updateAccount")
    public void updateAccount(@RequestBody AccountDto accountDto) {
        iOutInfoService.updateAccount(accountDto);
    }


    @ApiOperation("贷款结清证明")
    @GetMapping("/getLoanUrl")
    public String getLoanUrl(@RequestParam Integer outId) {
        Contract contract = contractMapper.selectOne(new LambdaQueryWrapper<Contract>().eq(Contract::getOutId, outId).eq(Contract::getType, SysConstant.CONTRACT_TYPE_TEN));
        if (ObjectUtil.isEmpty(contract)) {
            throw new XkdException("该订单未生成贷款结清证明");
        } else {
            return contract.getContract();
        }
    }


}
